import db from "../models/index.js";
import {clearObject, getNow} from "../utils/utils.js";

let user = db.user;
let userDao = {

};

// 查询用户通过username或者email
userDao.getUserByUsernameOrEmail = (username, email) => {
  return user.findOne({
    where: clearObject({username, email}),
    raw: true
  });
};

// 查询用户通过id
userDao.getUserById = (id) => {
  return user.findOne({
    attributes: ['id', 'username', 'email', 'invitation_code', 'inviter_id', 'create_time'],
    where: {id},
    raw: true
  });
};

// 查询用户邮箱通过id
userDao.getUserEmailById = (id) => {
  return user.findOne({
    attributes: ['email'],
    where: {id},
    raw: true
  });
};

// 添加用户 暂不考虑事务
userDao.addUser = async (username, password, email, invitation_code, inviter_id) => {
  let now = getNow();
  let newUser = await user.create({username, password, email, invitation_code, inviter_id, create_time: now});
  return newUser.dataValues;
};

// 邮箱和密码一致性验证 暂不考虑事务
userDao.checkUserWithEmail = (email, password) => {
  return user.findOne({
    where: {email, password}
  });
};

// 用户名和密码一致性验证验证
userDao.checkUserWithUsername = (username, password) => {
  return user.findOne({
    where: {username, password},
    raw: true
  });
};
// 用id和密码一致性验证验证
userDao.checkUserWithId = (id, password) => {
  return user.findOne({
    where: {id, password},
    raw: true
  });
};

// 验证邮箱是否存在
userDao.hasEmail = async (email) => {
  let count = await user.count({
    where: {email}
  });
  return count !== 0;
};

// 验证用户名是否存在
userDao.hasUsername = async (username) => {
  let count = await user.count({
    where: {username}
  });
  return count !== 0;
};

// 获取总用户的数量
userDao.getTotalUser = () => {
  return user.count();
};

// 验证邀请码是否存在
userDao.getInviterID = async (invitation_code) => {
  let userId = await user.findOne({
    attributes: ['id'],
    where: {invitation_code},
    raw: true
  });
  return userId && userId.id;
};

// 获取邀请的人数
userDao.userInviteCount = async (id) => {
  let count = await user.count({
    where: {inviter_id: id},
  });
  return count;
};

// 修改用户的数据
userDao.updatePassword = async (id, password, t) => {
  if(!t) {
    return user.update({password}, {where: {id}});
  }
  return user.update({password}, {where: {id}, transaction: t});
};

export default userDao;
